﻿using Asp.Versioning;
using FlyingEye.DeviceMaintenance.Repositories;
using FlyingEye.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace FlyingEye.Controllers
{
    [ApiVersion("1.0")]
    [Route("api/device-ops-service/v{version:apiVersion}/device-part-checked-results")]
    [ControllerName("DevicePartCheckedResult")]
    [Authorize]
    public class DevicePartCheckedResultController : DefaultController
    {
        private readonly IDevicePartCheckedResultRepository _devicePartCheckedResultRepository;

        public DevicePartCheckedResultController(IDevicePartCheckedResultRepository devicePartCheckedResultRepository)
        {
            _devicePartCheckedResultRepository = devicePartCheckedResultRepository;
        }

        [HttpPost("{id}/pass")]
        public async Task<OkResult> PassAsync(Guid id)
        {
            return await this.ActionInvokeAsync(async () =>
            {
                var model = await _devicePartCheckedResultRepository.FindAsync(id);

                if (model == null)
                {
                    throw new ResourceNotFoundException("校验项不存在！");
                }

                if (model.IsPassed)
                {
                    throw new BusinessOperationException("校验项已通过！");
                }

                model.IsPassed = true;
                await _devicePartCheckedResultRepository.UpdateAsync(model);
            });
        }

        [HttpPost("{id}/fail")]
        public async Task<OkResult> FailAsync(Guid id)
        {
            return await this.ActionInvokeAsync(async () =>
            {
                var model = await _devicePartCheckedResultRepository.FindAsync(id);

                if (model == null)
                {
                    throw new ResourceNotFoundException("校验项不存在！");
                }

                if (!model.IsPassed)
                {
                    throw new BusinessOperationException("校验项未检验！");
                }

                model.IsPassed = false;
                await _devicePartCheckedResultRepository.UpdateAsync(model);
            });

        }
    }
}
